

#include <stdlib.h>
#include <stdio.h>

#include "../../include/stack.h"
#include "../../include/list.h"

void print_stack(const stack_t *stack)
{
	unsigned int idx = 0;
	list_node_t *n;
	
	fprintf(stdout, "stack size is %d\n", list_size(stack));

	n = list_head(stack);

	while (idx < list_size(stack))
	{
		fprintf(stdout, "stack[%d] == %d\n", idx, *(int *)n->data);
		idx++;
		n = list_next(n);
	}

	return;
}

int main(int argc, char *argv[])
{
	stack_t stack;
	int *data;
	unsigned int idx;

	stack_init(&stack, free);

	fprintf(stdout, "Pushing 10 elements\n");

	for (idx = 0; idx < 10; idx++)
	{
		data = (int *)malloc(sizeof(int));
		if (!data)
			return -1;

		*data = idx + 1;
		if (stack_push(&stack, data))
			return -1;
	}

	print_stack(&stack);

	fprintf(stdout, "Poping 5 elements\n");
	for (idx = 0; idx < 5; idx++)
	{
		if (stack_pop(&stack, (void **)&data))
			return -1;
		else
			free(data);
	}

	print_stack(&stack);

	fprintf(stdout, "pushing 100 & 200\n");
	data = (int *)malloc(sizeof(int));
	if (!data)
		return -1;

	*data = 100;

	if (stack_push(&stack, data))
		return -1;

	data = (int *)malloc(sizeof(int));
	if (!data)
		return -1;

	*data = 200;

	if (stack_push(&stack, data))
		return -1;

	print_stack(&stack);

	data = stack_peek(&stack);
	if (!data)
		fprintf(stdout, "stack_peek top element, value == NULL\n");
	else
		fprintf(stdout, "stack_peek top element, value == %d\n", *data);

	print_stack(&stack);

	fprintf(stdout, "poping out all elements\n");

	while (stack_size(&stack))
	{
		if (!stack_pop(&stack, (void **)&data))
			free(data);
	}

	print_stack(&stack);

	fprintf(stdout, "destroying stack\n");
	stack_destroy(&stack);

	return 0;
}
